<?php
/**
 * Create By: PhpStorm
 * User: yuanxuncheng
 * File: Register.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\user;

use app\api\model\dao\UserAccount;
use app\api\model\dao\UserAuths;
use think\Exception;
use app\library\Error;
use app\library\CommonConfig;
use app\library\PageBase;
use think\Validate;
use think\Cache;
use app\library\Common;
use think\Log;
use think\Session;
use app\library\WechatAuth;
use app\library\Ip;

class Login extends PageBase
{

    private $objUserAccount;
    private $objUserAuths;
    private $objWechatAuth;

    public function __construct()
    {
        parent::__construct();

        $this->objUserAccount = new UserAccount();
        $this->objUserAuths = new UserAuths();
        $this->objWechatAuth = new WechatAuth();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'identity_type' => 'require',
            'identifier' => 'require',
            'credential' => 'require',
        ];
        $msg = [
            'identity_type.require' => '账号类型必填',
            'identifier.require' => '账号必填',
            'credential.require' => '密码必填',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {

        // TODO:业务逻辑
        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            Log::alert(__METHOD__ . ' param: ' . json_encode($param));
            return $this->getRes(Error::ERR_PARAM);
        }

        $time = time();
        if ($param['identity_type'] == 1) {
            $result = $this->objUserAuths->getUserAuths($param['identity_type'], $param['identifier']);
            if (count($result)) {
                $userid = $result[0]['user_id'];
                $identifier = $result[0]['identifier'];
                $credential = $result[0]['credential'];
                if (Common::encodePassword($param['credential']) == $credential) {

                    $user = $this->objUserAccount->getUserAccountByUserids($userid);
                    //return var_dump($user);
                    $sessionid = Common::getToken();
                    $userinfo = array(
                        'token' => $sessionid,
                        'userid' => $userid,
                        'last_time' => time(),
                    );
                    $user[0] = $user[0]->toArray();
                    if (!empty($user[0]['extend_info'])) {
                        $extend_info = json_decode($user[0]['extend_info'], true);
                        $user[0] = array_merge($user[0], $extend_info);
                    }
                    $userinfo = array_merge($userinfo, $user[0]);
                    Cache::set($sessionid, json_encode($userinfo), CommonConfig::TOKEN_EXPIRE_TIME);
                    $this->data = $userinfo;
                } else {
                    Log::alert(__METHOD__ . ' ret: ' . json_encode($param));
                    return $this->getRes(Error::ERR_PASSWORD);
                }
            } else {
                Log::alert(__METHOD__ . ' ret: ' . json_encode($param));
                return $this->getRes(Error::ERR_USER_NOT_EXIST);
            }
        }

        if ($param['identity_type'] == 2 && !empty($param['code'])) {
            $code = $param['code'];
            $openid = $param['identifier'];
            $result = $this->objUserAuths->getUserAuths($param['identity_type'], $openid);
            if (count($result)) {
                $userid = $result[0]['user_id'];
                $user = $this->objUserAccount->getUserAccountByUserids($userid);

                $userinfo = array(
                    'token' => $openid,
                    'userid' => $userid,
                    'last_time' => time(),
                );
                $user[0] = $user[0]->toArray();
                if (!empty($user[0]['extend_info'])) {
                    $extend_info = json_decode($user[0]['extend_info'], true);
                    $user[0] = array_merge($user[0], $extend_info);
                }
                $userinfo = array_merge($userinfo, $user[0]);
                Cache::set($openid, json_encode($userinfo), CommonConfig::TOKEN_EXPIRE_TIME);
                $this->data = $userinfo;
            } else {
                $huanxin_username = Common::encryptString($param['identifier']);
                //    $nick_name = $user_info['nickname'];
                //    $sex = $user_info['sex'];
                $addUserAccount = array();
                $addUserAccount['user_name'] = 'ms' . $param['code'];
                $addUserAccount['nick_name'] = 'ms' . $param['code'];
                $addUserAccount['phone'] = $param['identifier'];
                $addUserAccount['reg_ip'] = Ip::getClientIp();
                $addUserAccount['reg_time'] = $time;
                $addUserAccount['create_time'] = $time;
                $addUserAccount['update_time'] = $time;
                $addUserAccount['extend_info'] = '';
                $addUserAccount['huanxin_username'] = $huanxin_username;
                $userid = $this->objUserAccount->addUserAccount($addUserAccount);
                if ($userid) {
                    $addUserAuths = array();
                    $addUserAuths['user_id'] = $userid;
                    $addUserAuths['identity_type'] = $param['identity_type'];
                    $addUserAuths['identifier'] = $openid;
                    $addUserAuths['credential'] = $openid;
                    $ret = $this->objUserAuths->saveUserAuths($addUserAuths);
                }

                $userinfo = array(
                    'token' => $openid,
                    'userid' => $userid,
                    'last_time' => time(),
                );
                if (!empty($user[0]['extend_info'])) {
                    $extend_info = json_decode($user[0]['extend_info'], true);
                    $user[0] = array_merge($user[0], $extend_info);
                }
                $userinfo = array_merge($userinfo, $user[0]);
                Cache::set($openid, json_encode($userinfo), CommonConfig::TOKEN_EXPIRE_TIME);
                $this->data = $userinfo;
            }
        }
        
        return $this->getRes();
    }
}
